// 引入数据库模块
const { connection, requestQuery } = require("../database/db"); //按需引入
//引入token模块
const opentoken = require("../utils/token");
//日期格式
var moment = require('moment');
//密码加密
var bcrypt = require('bcryptjs');
// 加密方式
const salt = bcrypt.genSaltSync(10);
// 随机生成图片验证码
const svgCaptcha = require('svg-captcha');
// 随机生成字符串
// const random = require("string-random");
const stringRandom = require("string-random");




// 定义一个临时的图片验证码
var tempcaptcha = null;
// 定义一个临时的短信验证码
var tempcode = null;
// 定义一个临时的手机号
var tempphone = null;


//用户列表
exports.Userlist = async(req, res) => {
    //get传值通过req.query {page:1，size:10}
    let page = req.query.page || 1;
    let size = req.query.size || 10;
    let index = (page - 1) * size;
    let sort = req.query.sort || "ASC";
    let countSql = `select count(*) from users`;
    let countResult = await requestQuery(countSql);
    console.log(countResult);
    let total = countResult[0]["count(*)"];
    let totalpage = Math.ceil(total / size)

    let userSql = `select * from users limit ${index},${size}`;

    let userListData = await requestQuery(userSql);


    res.json({
        status: 200,
        count: total,
        page: page,
        totalpage: totalpage,
        size: size,
        data: userListData
    })
}

// 修改接口
exports.edituser = async(req, res) => {
    let edituserSql = `update users set user_name="${req.body.user_name}",phone="${req.body.phone}",imgsrc="${req.body.imgsrc}" where user_id=${req.body.user_id}`
    let result = await requestQuery(edituserSql);
    res.json({
        status: 200,
        msg: "修改成功",
        data: result
    })
}

// 修改is_show
exports.editisShow = async(req, res) => {
    let editsql = `update users set is_show="${req.body.is_show}" where user_id=${req.body.user_id}`;
    let result = await requestQuery(editsql);
    res.json({
        status: 200,
        msg: "is_show已修改",
        data: result
    })
}

// 删除用户
exports.deleUser = async(req, res) => {
    console.log(req)
    let delesql = `delete from users where user_id=${req.query.user_id}`;
    let result = await requestQuery(delesql);
    res.json({
        status: 200,
        msg: "已删除",
        data: result
    })
}

// 查询所有数据
exports.alluser = async(req, res) => {
    let allusersql = `select * from users`;
    let result = await requestQuery(allusersql);
    res.json({
        status: 200,
        mag: "查询完成",
        data: result
    })
}


//用户注册  post请求
exports.UserRegister = (req, res) => {
    console.log(req.body);
    let user_name = req.body.user_name;
    let user_password = req.body.user_password;
    let phone = req.body.phone;
    let imgsrc = req.body.imgsrc;
    // 格式化时间
    let nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询用户名是否存在
    let user_name_sql = `select user_name from users where user_name=? and is_show=1`;
    connection.query(user_name_sql, user_name, (err, result_name) => {
        if (err) {
            return res.json({
                msg: "用户注册失败1",
                status: 1001,
                data: err
            })
        }
        console.log(result_name); //如果result_name是一个空数组，说明该用户名可用
        if (result_name == "") {
            //如果条件成立，在判断手机号是否存在
            let phone_sql = `select phone from users where phone=? and is_show=1`;
            connection.query(phone_sql, phone, (err, result_phone) => {
                if (err) {
                    return res.json({
                        msg: "用户注册失败2",
                        status: 1002,
                        data: err
                    })
                }
                if (result_phone == "") {
                    // 如果result_phone是一个空数组，说明该用户名可用
                    let register_sql = `insert into users set user_name=?,user_password=?,phone=?,imgsrc=?,create_time='${nowTime}'`
                        //加密密码
                    let hashPassword = bcrypt.hashSync(user_password, salt);
                    connection.query(register_sql, [user_name, hashPassword, phone, imgsrc], (err, data) => {
                        if (err) {
                            return res.json({
                                msg: "用户注册失败3",
                                status: 1003,
                                data: err
                            })
                        }
                        console.log(data);
                        if (data.affectedRows == 1) {
                            return res.json({
                                msg: "注册成功",
                                status: 200,
                                data: data
                            })
                        }
                    })

                } else {
                    return res.json({
                        msg: "手机号存在",
                        status: 1004,
                        data: err
                    })
                }
            })
        } else {
            return res.json({
                msg: "用户户名存在",
                status: 1005,
                data: err
            })
        }
    })
}

//用户登录
exports.Login = (req, res) => {
    let user_name = req.body.user_name;
    let captcha = req.body.captcha;
    if (captcha != tempcaptcha) {
        return res.json({
            msg: "验证码不正确",
            status: 001,
            data: err
        })
    };
    // let user_password = req.body.user_password;
    // console.log(User_name);
    // console.log(user_password);
    let user_name_sql = `select user_name,user_password from users where user_name=?`;
    connection.query(user_name_sql, [user_name], (err, data) => {
        if (err) {
            return res.json({
                msg: "数据库查询失败",
                status: 5001,
                data: err
            })
        }
        if (data.length == 0) {
            //成立说明用户名不存在
            return res.json({
                msg: "该用户不存在,请注册",
                status: 404,
                data: err
            })
        } else {
            // 验证密码
            let check_user_password = bcrypt.compareSync(req.body.user_password, data[0].user_password);
            console.log(check_user_password);
            if (!check_user_password) {
                return res.json({
                    msg: "密码错误",
                    status: 404
                })
            } else {
                const token = opentoken.createToken({
                    user_name: user_name,
                    isLogin: true
                });
                opentoken.checkToken(token).then(result => {
                    console.log(result);
                });
                return res.json({
                    msg: "登录成功",
                    status: 200,
                    token: token,
                    data: data
                })
            }
        }
    })
}

// 短信登陆的图片验证码
exports.svgCaptcha = (req, res) => {
    // 配置验证码
    var captcha = svgCaptcha.create({
        size: 4, //几位验证码
        ignoreChars: '0o1i', //忽略的字符
        noise: 2, //干扰线
        color: true, //字体颜色
        background: "#fff" //背景色
    });
    res.type("svg");
    tempcaptcha = captcha.text.toLowerCase();
    res.status(200).send(captcha.data);
    console.log(captcha.text);
};

// 短信验证码控制器
exports.MessageCode = (req, res) => {
    //第一步:输入正确的手机号
    //第二步：点击获取验证码，发起请求
    //第三步：发送短信的内容+随机的验证码
    let codeStr = ("000000" + Math.floor(Math.random() * 999999)).slice(-6);
    tempcode = codeStr;
    tempphone = req.body.phone;
    res.json({
        msg: "发送成功",
        code: codeStr,
        status: 200
    })
};

//短信登陆接口
exports.PhoneLogin = async(req, res) => {
    //post来提交数据
    //req.body  {phone:"13673618137","captcha":"abcd",code:"123456"}
    //在该接口中要验证短信验证码和图片验证码
    console.log(tempcaptcha);
    console.log(tempcode);
    console.log(tempphone);
    //获取用户提交的数据
    let phone = req.body.phone;
    let code = req.body.code;
    let captcha = req.body.captcha.toLowerCase();

    if (tempcaptcha != captcha) {
        return res.json({
            msg: "图片验证码不正确",
            status: 1001
        })
    } else if (tempcode != code) {
        return res.json({
            msg: "短信验证码不正确",
            status: 1002
        })
    } else if (tempphone != phone) {
        return res.json({
            msg: "手机号不正确",
            status: 1003
        })
    } else {
        //到这来说明上边条件都成立了
        //判断手机号是否存在
        //1、手机号不存在，将该手机号注册到数据库
        let phone_sql = `SELECT * from users WHERE phone=? AND is_show=1`
        let phone_result = await requestQuery(phone_sql, phone)
        if (phone_result.length == 0) {
            //如果条件成立说明手机号不存在，需要将手机号注册到数据库
            let user_name = "hg_" + stringRandom(10) + new Date().getTime()
            let nowTime = moment().format("YYYY-MM-DD HH:mm:ss")
            let userSql = `INSERT INTO users (user_name,phone,is_show,create_time) VALUES ("${user_name}","${phone}","1","${nowTime}")`
            let result = await requestQuery(userSql)
            if (result.affectedRows == 1) {
                return res.json({
                    msg: "登录成功",
                    status: 200,
                    data: result
                })
            } else {
                return res.json({
                    msg: "服务器错误",
                    status: 5001
                })
            }
        } else {
            //2、手机号存在，直接登录即可
            return res.json({
                msg: "登录成功",
                status: 200,
                data: phone_result
            })
        }
    }
}


exports.Adduser = (req, res) => {
    let user_name = req.body.user_name;
    let user_password = req.body.user_password;
    let phone = req.body.phone;
    let captcha = req.body.captcha.toLowerCase();
    let nowTime = moment().format("YYYY-MM-DD HH:mm:ss");

    let user_name_sql = `select user_name from users where user_name=? and is_show=1`;
    connection.query(user_name_sql, user_name, (err, result_name) => {
        if (err) {
            return res.json({
                msg: "用户存在",
                status: 0201,
                data: err
            })
        }
        if (result_name == "") {
            let phone_sql = `select phone from users where phone=? and is_show=1`;
            connection.query(phone_sql, phone, (err, result_phone) => {
                if (err) {
                    return res.json({
                        msg: "错误信息1",
                        status: 0202,
                        data: err
                    })
                }
                if (result_phone == "" && tempcaptcha == captcha) {
                    // let register_sql = `insert into users set user_name=?,user_password=?,phone=?,is_show=1`;
                    let register_sql = `insert into users set user_name=?,user_password=?,phone=?,is_show=1,create_time='${nowTime}'`
                    let hashPassword = bcrypt.hashSync(user_password, salt);
                    connection.query(register_sql, [user_name, hashPassword, phone], (err, data) => {
                        if (err) {
                            return res.json({
                                msg: "错误信息3",
                                status: 0203,
                                data: err
                            })
                        }
                        console.log(data);
                        if (data.affectedRows == 1) {
                            return res.json({
                                msg: "注册成功",
                                status: 200,
                                data: data
                            })
                        }
                    })
                } else {
                    return res.json({
                        msg: "手机号存在",
                        status: 1004,
                    })
                }
            })
        } else {
            return res.json({
                msg: "用户户名存在",
                status: 1005,
            })
        }
    })
}